﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio
Copyright (c) 2011,      Zynga Inc.
Copyright (c) 2008-2010, Ricardo Quesada

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace PKEngine
{
	/// <summary>
	/// Main controller of engine. Will handle the main window and manage scenes.
	/// </summary>
	public class PKGame
	{
		#region Singleton
		private static PKGame _sharedGame;

		public static PKGame SharedGame
		{
			get
			{
				if (_sharedGame == null)
				{
					_sharedGame = new PKGame();
				}
				return _sharedGame;
			}
		}
		#endregion

		#region Public Properties
		public PKScene RunningScene { get; private set; }
		public float AnimationInterval { get; private set; }
		public bool NextDeltaTimeZero { get; set; }
		public bool IsPaused { get; private set; }
		public bool NeedCleanupScene { get; private set; }
		#endregion

		#region Private Fields
		private PKScene nextScene;
		private Stack<PKScene> scenesStack;

		private float lastUpdate;
		private float deltaTime;

		private PictureBox bindingMainScreen;
		private bool runningMainLoop;

#if DEBUG
		private int frameCount;
		private float frameTime;
#endif
		#endregion

		#region Initialization
		private PKGame()
		{
			this.RunningScene = null;
			this.nextScene = null;
			this.scenesStack = new Stack<PKScene>();

			this.bindingMainScreen = null;
			this.runningMainLoop = true;

			this.AnimationInterval = 1.0f / PKConfig.SharedConfig.FramePerSecond;
			this.NextDeltaTimeZero = true;
			this.IsPaused = false;
		}
		#endregion

		#region Public Methods
		#region Scene Management
		/// <summary>
		/// Starts game with a scene.
		/// Call this method for the first scene.
		/// Do not use this method if there is a running scene.
		/// </summary>
		/// <param name="scene">Target scene</param>
		public void RunWithScene(PKScene scene)
		{
			Debug.Assert(scene != null, "PKGame.RunWithScene: Argument cannot be null.");
			Debug.Assert(RunningScene == null, "PKGame.RunWithScene: Cannot run a scene when another scene is running. Use ReplaceScene or PushScene instead.");

			this.PushScene(scene);
			lastUpdate = PKTime.GetTime();
			deltaTime = 0;
		}

		/// <summary>
		/// Replaces the running scene with the given scene.
		/// The original running scene will be released.
		/// Make sure there is a running scene.
		/// </summary>
		/// <param name="scene">Target scene</param>
		public void ReplaceScene(PKScene scene)
		{
			Debug.Assert(scene != null, "PKGame.ReplaceScene: Argument cannot be null.");
			Debug.Assert(RunningScene != null, "PKGame.ReplaceScene: A running scene is needed.");

			NeedCleanupScene = true;
			scenesStack.Pop();
			scenesStack.Push(scene);
			nextScene = scene;
		}

		/// <summary>
		/// Saves the running scene and runs the new scene.
		/// Do not save a lot of scene in stack to save memory.
		/// Call this mathod when there is a running scene.
		/// </summary>
		/// <param name="scene">Target scene</param>
		public void PushScene(PKScene scene)
		{
			Debug.Assert(scene != null, "PKGame.PushScene: Argument cannot be null.");

			NeedCleanupScene = false;
			scenesStack.Push(scene);
			nextScene = scene;
		}

		/// <summary>
		/// Pops a scene from stack and runs it.
		/// The running scene will be released.
		/// Make sure there is at least one scene in the stack. Or the game will be ended.
		/// Call this mathod when there is a running scene.
		/// </summary>
		public void PopScene()
		{
			Debug.Assert(RunningScene != null, "PKGame.PopScene: A running scene is needed.");

			scenesStack.Pop();
			if (scenesStack.Count == 0)
			{
				this.End();
			}
			else
			{
				NeedCleanupScene = true;
				nextScene = scenesStack.Peek();
			}
		}

		/// <summary>
		/// Pops out all scenes from the queue until the root scene in the queue.
		/// The running scene will be released.
		/// Make sure there is at least one scene in the stack. Or the game will be ended.
		/// Call this mathod when there is a running scene.
		/// </summary>
		public void PopToRootScene()
		{
			Debug.Assert(RunningScene != null, "PKGame.PopToRootScene: A running scene is needed.");

			if (scenesStack.Count == 1)
			{
				scenesStack.Clear();
				this.End();
			}
			else
			{
				while (scenesStack.Count > 1)
				{
					PKScene current = scenesStack.Pop();
					if (current.IsRunning)
					{
						current.OnExit();
					}
					current.Cleanup();
				}
				NeedCleanupScene = false;
				nextScene = scenesStack.Peek();
			}
		}
		#endregion

		#region Main Features
		/// <summary>
		/// Draw the scene.
		/// </summary>
		public void DrawScene()
		{
			this.CalculateDeltaTime();

			if (!IsPaused)
			{
				PKScheduler.SharedScheduler.Update(deltaTime);
			}

			if (nextScene != null)
			{
				this.SetNextScene();
			}

			PKMainSurface.SharedMainSurface.ClearClippingRects();
			PKMainSurface.SharedMainSurface.Clear(false);

			if (RunningScene != null)
			{
				RunningScene.Visit();
			}

			for (int i = 0; i < 3; i++)
			{
				if (PKMainSurface.SharedMainSurface.ShowOnMainScreen())
				{
					break;
				}
			}

#if DEBUG
			this.ShowFPS();
#endif
		}

		/// <summary>
		/// Main loop of game.
		/// </summary>
		public void MainLoop(PictureBox mainScreen)
		{
			Debug.Assert(mainScreen != null, "PKGame.MainLoop: Argument cannot be null.");

			bindingMainScreen = mainScreen;

			if (!PKMainSurface.SharedMainSurface.BindToMainScreen(mainScreen))
			{
				this.End();
			}

			while (runningMainLoop)
			{
				float now = PKTime.GetTime();
				if (now - lastUpdate >= AnimationInterval)
				{
					this.DrawScene();
					Thread.Sleep(1);
				}
			}

			Application.Exit();
		}

		/// <summary>
		/// Ends the game.
		/// </summary>
		public void End()
		{
			PKMouseDispatcher.SharedDispatcher.ClearHandlers();
			PKKeybdDispatcher.SharedDispatcher.ClearHandlers();

			if (RunningScene != null)
			{
				RunningScene.OnExit();
				RunningScene.Cleanup();
			}

			RunningScene = null;
			nextScene = null;
			scenesStack.Clear();

			bindingMainScreen = null;
			runningMainLoop = false;
		}

		/// <summary>
		/// Pause the running scene.
		/// The running scene will be drawn with 3 FPS.
		/// All scheduled timers will be paused.
		/// </summary>
		public void Pause()
		{
			if (IsPaused)
			{
				return;
			}

			AnimationInterval = 10.0f / PKConfig.SharedConfig.FramePerSecond;
			IsPaused = true;

#if DEBUG
			if (bindingMainScreen != null)
			{
				Form parentForm = bindingMainScreen.Parent as Form;
				parentForm.Text = PKConfig.SharedConfig.GameName + " - Paused";
			}
#endif
		}

		/// <summary>
		/// Resume the running scene.
		/// </summary>
		public void Resume()
		{
			if (!IsPaused)
			{
				return;
			}

			AnimationInterval = 1.0f / PKConfig.SharedConfig.FramePerSecond;
			lastUpdate = PKTime.GetTime();
			deltaTime = 0;
			IsPaused = false;

#if DEBUG
			if (bindingMainScreen != null)
			{
				Form parentForm = bindingMainScreen.Parent as Form;
				parentForm.Text = PKConfig.SharedConfig.GameName;
			}
#endif
		}
		#endregion
		#endregion

		#region Private Methods
		private void CalculateDeltaTime()
		{
			float now = PKTime.GetTime();

			if (NextDeltaTimeZero)
			{
				deltaTime = 0;
				NextDeltaTimeZero = false;
			}
			else
			{
				deltaTime = now - lastUpdate;
				deltaTime = Math.Max(0, deltaTime);
			}

#if DEBUG
			// If we are debugging our code, prevent big delta time.
			if (deltaTime > AnimationInterval)
			{
				deltaTime = AnimationInterval;
			}
#endif

			lastUpdate = now;
		}

		private void SetNextScene()
		{
			bool runningIsTransition = RunningScene is PKTransitionScene;
			bool nextIsTransition = nextScene is PKTransitionScene;

			if (!nextIsTransition && RunningScene != null)
			{
				RunningScene.OnExit();

				if (NeedCleanupScene)
				{
					RunningScene.Cleanup();
				}
			}

			RunningScene = nextScene;
			nextScene = null;

			if (!runningIsTransition)
			{
				RunningScene.OnEnter();
			}
		}

#if DEBUG
		private void ShowFPS()
		{
			frameCount++;
			frameTime += deltaTime;
			if (frameCount >= PKConfig.SharedConfig.FramePerSecond)
			{
				if (bindingMainScreen != null)
				{
					Form parentForm = bindingMainScreen.Parent as Form;
					parentForm.Invoke(new MethodInvoker(delegate() { parentForm.Text = PKConfig.SharedConfig.GameName + " - FPS:" + (frameCount / frameTime).ToString("0.00"); }));
				}
				frameCount = 0;
				frameTime = 0;
			}
		}
#endif
		#endregion
	}
}
